package com.ziyun.pop.modules.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.utility.StringUtils;
import com.ziyun.pop.modules.freightages.entity.FreightTemplateEntity;
import com.ziyun.pop.modules.freightages.service.FreightAreaService;
import com.ziyun.pop.modules.freightages.service.FreightTemplateService;
import com.ziyun.pop.modules.goods.TwbVo.TwbGoodsListVo;
import com.ziyun.pop.modules.goods.TwbVo.TwbStateCollectVo;
import com.ziyun.pop.modules.goods.dao.ErpGoodsDao;
import com.ziyun.pop.modules.goods.entity.GoodsEntity;
import com.ziyun.pop.modules.goods.entity.GoodsImageEntity;
import com.ziyun.pop.modules.goods.service.GoodsService;
import com.ziyun.pop.modules.goods.vo.GoodsInfoVo;
import com.ziyun.pop.modules.goods.vo.GoodsSalesVo;
import com.ziyun.pop.modules.goodsCraftPrice.entity.GoodsCraftPriceEntity;
import com.ziyun.pop.modules.goodsCraftPrice.service.GoodsCraftPriceService;
import com.ziyun.pop.modules.goodsProduct.entity.GoodsProductEntity;
import com.ziyun.pop.modules.goodsProduct.service.GoodsProductService;
import com.ziyun.pop.modules.productBaseInfo.entity.ProductBaseInfoEntity;
import com.ziyun.pop.modules.productBaseInfo.service.ProductBaseInfoService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<ErpGoodsDao, GoodsEntity> implements GoodsService {
    @Autowired
    private GoodsCraftPriceService goodsCraftPriceService;

    @Autowired
    private GoodsProductService goodsProductService;

    @Autowired
    private ProductBaseInfoService productBaseInfoService;

    @Autowired
    private FreightTemplateService freightTemplateService;

    @Autowired
    private FreightAreaService freightAreaService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<GoodsEntity> page = (Page<GoodsEntity>) this.page(
                new Query<GoodsEntity>(params).getPage(),
                new QueryWrapper<GoodsEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public R copyGoods(Long sellerId, Long fromSellerId) {
        Date nowDate = new Date();
        String createName = "admin";
        // 先判断该商家 是有工艺价格
        int count = this.goodsCraftPriceService.count(new QueryWrapper<GoodsCraftPriceEntity>().eq("seller_id", sellerId));
        if (count == 0) {
            //不存在 则同步
            List<GoodsCraftPriceEntity> goodsCraftPriceList = this.goodsCraftPriceService.list(new QueryWrapper<GoodsCraftPriceEntity>()
                    .eq("seller_id", fromSellerId)
                    .eq("del_flag", 0));
            // 循环处理 准备插入
            for (GoodsCraftPriceEntity goodsCraftPrice : goodsCraftPriceList) {
                goodsCraftPrice.setCraftPriceId(null);
                goodsCraftPrice.setSellerId(sellerId); // 重置sellerId
                goodsCraftPrice.setCreateName(createName);
                goodsCraftPrice.setCreateTime(nowDate);
            }
            // 批量插入
            this.goodsCraftPriceService.saveBatch(goodsCraftPriceList);
        }
        // 处理运费模板
        List<FreightTemplateEntity> freightTemplateList = this.freightTemplateService.list(new QueryWrapper<FreightTemplateEntity>()
                .eq("seller_id",sellerId)
                .eq("template_name","通用运费模版")
                .eq("disabled",0)
                .eq("free_shipping",0));
        Integer freightId = null;
        if (freightTemplateList.size() ==0){
            freightId = this.initFreightTemplate(sellerId);
        }else {
            freightId = freightTemplateList.get(0).getTemplateId();
        }


        // 查询 待同步商品
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("sellerId", sellerId);
        paramsMap.put("fromSellerId", fromSellerId);
        List<GoodsEntity> goodsList = this.baseMapper.queryCopyGoodsList(paramsMap);

        // 循环goods
        for (GoodsEntity goods : goodsList) {
            Long oldGoodsId = goods.getGoodsId();
            goods.setGoodsId(null);
            goods.setBrandId(null);
            goods.setGoodsNo(builderGoodsBn(goods.getCategoryId()));
            goods.setSellerId(Integer.valueOf(sellerId.toString()));
            //goods.setMarketable("puton"); //默认上架
            goods.setTwbPushFlag(false);
            goods.setInfoUrls(null);
            goods.setSelf(false);
            goods.setFreightId(freightId);
            goods.setStageType(1);
            goods.setExamineStatus(1);
            goods.setCreateName(createName);
            goods.setCreateTime(nowDate);
            goods.setZiyunGoodsId(oldGoodsId);
            goods.setDefaultGoods(0);
           /* String imageUrls =  goods.getImageUrls();
            // 图片特殊处理
            List<String> temp = new ArrayList<>();
            if (StringUtil.isNotEmpty(imageUrls)){
                String[] imageUrlArr = imageUrls.split(",");
                for (int i=0; i< imageUrlArr.length; i++){
                    if (StringUtil.isNotEmpty(imageUrlArr[i])){ //去除空格
                        temp.add(imageUrlArr[i]);
                    }
                }
                // 随机打乱顺序
                Collections.shuffle(temp);
                String newImageUrls = StringUtils.join(temp.toArray(), ",");
                goods.setImageUrls(newImageUrls);

            }*/
            // 插入Goods 返回新ID
            this.save(goods);
            //再插入图片
            List<GoodsImageEntity> goodsImageList = this.baseMapper.queryGoodsImage(oldGoodsId);
            for (GoodsImageEntity goodsImage : goodsImageList){
                goodsImage.setRelationId(goods.getGoodsId());
                goodsImage.setCreateName(createName);
                goodsImage.setCreateTime(nowDate);
            }
            // 批量插入图片
            if (goodsImageList.size() >0){
                this.baseMapper.insertGoodsImage(goodsImageList);
                //再查询出图片 放入goods  imageUrls
                List<GoodsImageEntity> newGoodsImageList = this.baseMapper.queryGoodsImage(goods.getGoodsId());
                List<Long> temp = new ArrayList<>();
                for (GoodsImageEntity goodsImageEntity :newGoodsImageList ){
                    temp.add(goodsImageEntity.getId());
                }
                Collections.shuffle(newGoodsImageList);
                GoodsEntity goodsTemp = new GoodsEntity();
                goodsTemp.setGoodsId(goods.getGoodsId());
                goodsTemp.setImageUrls(StringUtils.join(temp.toArray(), ","));
                this.updateById(goodsTemp);
            }




            //查询 goods_product
            List<GoodsProductEntity> goodsProductList = this.goodsProductService.list
                    (new QueryWrapper<GoodsProductEntity>().eq("goods_id", oldGoodsId));
            // 循环 goods_product
            for (GoodsProductEntity goodsProduct : goodsProductList) {
                goodsProduct.setProductId(null);
                goodsProduct.setGoodsId(goods.getGoodsId());
                //goodsProduct.setMarketable("puton");//默认上架
                goodsProduct.setStageType(1);
                goodsProduct.setCreateName(createName);
                goodsProduct.setCreateTime(nowDate);
            }
            // 批量插入
            this.goodsProductService.saveBatch(goodsProductList);

            //查询 product_base_info
            List<ProductBaseInfoEntity> productBaseInfoList = this.productBaseInfoService.list
                    (new QueryWrapper<ProductBaseInfoEntity>().eq("goods_id", oldGoodsId));
            for (ProductBaseInfoEntity productBaseInfo : productBaseInfoList) {
                productBaseInfo.setId(null);
                productBaseInfo.setGoodsId(goods.getGoodsId());
                productBaseInfo.setCreateUser(createName);
                productBaseInfo.setCreateDate(nowDate);
            }
            // 批量插入
            this.productBaseInfoService.saveBatch(productBaseInfoList);
        }

        return R.ok("同步成功!");
    }

    @Override
    public R copyGoodsCraftPriceTemplate(Long sellerId, Long fromSellerId) {
        // 查询 待同步运费模板
        Date nowDate = new Date();
        String createName = "admin";
       List<GoodsCraftPriceEntity> goodsCraftPriceList = this.goodsCraftPriceService.selectWaitSync( sellerId,  fromSellerId);
       if (goodsCraftPriceList.size() >0){
           // 循环处理 准备插入
           for (GoodsCraftPriceEntity goodsCraftPrice : goodsCraftPriceList) {
               goodsCraftPrice.setCraftPriceId(null);
               goodsCraftPrice.setSellerId(sellerId); // 重置sellerId
               goodsCraftPrice.setCreateName(createName);
               goodsCraftPrice.setCreateTime(nowDate);
           }
           // 批量插入
           this.goodsCraftPriceService.saveBatch(goodsCraftPriceList);
       }

       // 处理运费模板
        // 处理运费模板
        List<FreightTemplateEntity> freightTemplateList = this.freightTemplateService.list(new QueryWrapper<FreightTemplateEntity>()
                .eq("seller_id",sellerId)
                .eq("template_name","通用运费模版")
                .eq("disabled",0)
                .eq("free_shipping",0));
        Integer freightId = null;
        if (freightTemplateList.size() ==0){
            freightId = this.initFreightTemplate(sellerId);
        }else {
            freightId = freightTemplateList.get(0).getTemplateId();
        }

        return R.ok().put("freightId",freightId);
    }

    private Integer initFreightTemplate(Long sellerId){
        // 查询该商家地区
        Integer regionId = this.baseMapper.getArea(sellerId);
        if (regionId == null) {
            throw new RRException("未查询到该商家地区!");
        }
        // 生成自提模板
        FreightTemplateEntity freightTemplate = new FreightTemplateEntity();
        freightTemplate.setTemplateName("自提运费模版");
        freightTemplate.setTemplateType("shop");
        freightTemplate.setFreeShipping(1);
        freightTemplate.setValuationWay("weight");
        freightTemplate.setFirstUnit(1);
        freightTemplate.setFirstPrice(BigDecimal.ZERO);
        freightTemplate.setContinueUnit(1);
        freightTemplate.setContinuePrice(BigDecimal.ZERO);
        freightTemplate.setDefTemplate(0);
        freightTemplate.setDisabled(0);
        freightTemplate.setSellerId(sellerId);
        freightTemplate.setProviderType("shop");
        freightTemplate.setCreateTime(new Date());
        freightTemplate.setCreateName("admin");
        this.freightTemplateService.save(freightTemplate);
        // 查找基础模板
        Map<String,Object> freightBase = this.baseMapper.getFreightBase(regionId,1321);
        if (freightBase == null){
            throw new RRException("未查询到运费基础数据");
        }
        BigDecimal startPrice =  BigDecimal.valueOf(Double.valueOf(freightBase.get("startPrice").toString()));
        BigDecimal stepPrice =  BigDecimal.valueOf(Double.valueOf(freightBase.get("stepPrice").toString()));
        //生成模板
        FreightTemplateEntity freightBaseTemplate = new FreightTemplateEntity();
        freightBaseTemplate.setTemplateName("通用运费模版");
        freightBaseTemplate.setTemplateType("shop");
        freightBaseTemplate.setFreeShipping(0);
        freightBaseTemplate.setValuationWay("weight");
        freightBaseTemplate.setFirstUnit(1);
        freightBaseTemplate.setFirstPrice(startPrice);
        freightBaseTemplate.setContinueUnit(1);
        freightBaseTemplate.setContinuePrice(stepPrice);
        freightBaseTemplate.setDefTemplate(1);
        freightBaseTemplate.setDisabled(0);
        freightBaseTemplate.setSellerId(sellerId);
        freightBaseTemplate.setProviderType("shop");
        freightBaseTemplate.setCreateTime(new Date());
        freightBaseTemplate.setCreateName("admin");
        this.freightTemplateService.save(freightBaseTemplate);
        // 再生成 freight_area
        this.freightAreaService.selectInsert(freightBaseTemplate.getTemplateId(), regionId);

        return freightBaseTemplate.getTemplateId();
    }

    /**
     * 图文宝根据商品名称获取商品信息
     *
     * @param params
     * @return
     */
    @Override
    public List<GoodsInfoVo> querySearchProduct(Map<String, Object> params) {
        return this.baseMapper.querySearchProduct(params);
    }

    @Override
    public List<GoodsSalesVo> getGoodsSalesList(Long sellerId) {
        return baseMapper.getGoodsSalesList(sellerId);
    }

    private String builderGoodsBn(Integer categoryId) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(sdf.format(date));
        stringBuffer.append(String.format("%6d", categoryId).replace(" ", "0"));
        stringBuffer.append(date.getTime());
        stringBuffer.append(String.format("%02d", random.nextInt(99)));
        return stringBuffer.toString();
    }

    /**
     * 小程序接口实现,获得商品商品数量统计
     * @param sellerId
     * @return
     */
    @Override
    public TwbStateCollectVo getTwbGoodsStateCount(Long sellerId) {
        return this.baseMapper.getTwbGoodsStateCount(sellerId);
    }

    @Override
    public List<GoodsEntity> twbHostGoods(Long sellerId) {
        return this.baseMapper.twbHostGoods(sellerId);
    }

    @Override
    public Page<TwbGoodsListVo> getTwbGoodsList(Map params) {
        Page<TwbGoodsListVo> goodsEntityPage = new Page<>();////marketable current size total
        goodsEntityPage.setSize((Integer)params.get("size"));
        goodsEntityPage.setCurrent((Integer)params.get("current"));
//		String marketable = (String) params.get("marketable");
//		Long sellerId = Long.valueOf(String.valueOf(params.get("sellerId")));
        goodsEntityPage.setRecords(this.baseMapper.queryTwbGoodsList(goodsEntityPage,params));

        return goodsEntityPage;
    }

}
